﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CS544_Protocol_Client.Forms;
using System.Collections;

namespace CS544_Protocol_Client.Forms
{

    /**
     * Author: Kelly Page,Brian Driscoll
     * Date Created: 2/22/2011
     * Date Updated: 3/4/2011
     * 
     * Purpose: Displays the main user interface and coordinates interface operations.
     * 
     **/

    public partial class ClientForm : Form
    {

        private ClientControl myClientControl; //chat client controller;
        private LoginForm myLoginForm;        
        private RegisterForm myRegisterForm;
        private List<ChatRoomForm> myChatRoomForms = new List<ChatRoomForm>();//holds open chat rooms        
        private List<PrivateMessageForm> myPrivateMessageForms = new List<PrivateMessageForm>(); //holds all Private message forms that are open
        private ChatRoomForm currentChatRoom;        
        public ClientForm(ClientControl clientController)
        {
            InitializeComponent();
            myClientControl = clientController;
            myRegisterForm = new RegisterForm(myClientControl);
            myLoginForm = new LoginForm(myClientControl);
            myClientControl.RegisterResult += new ClientEventHandler(myClientControl_RegisterResult);
            myClientControl.LoginResult += new ClientEventHandler(myClientControl_LoginResult);
            myClientControl.NewPrivateMessage += new ClientEventHandler(myClientControl_NewPrivateMessage);           
            myClientControl.LogoutResult += new ClientEventHandler(myClientControl_LogoutResult);
            myClientControl.Registering += new EventHandler(myClientControl_Registering);             
            this.FormClosed += new FormClosedEventHandler(ClientForm_FormClosed);
        }
        



        void myClientControl_Registering(object sender, EventArgs e)
        {
             this.CurrentStatusLabel.Text = "Connected, Registering as " + myClientControl.currentUser.Username;
             this.StatusPanel.BackColor = Color.LightSalmon;
        }   


        
        //Handle when form is closed
        void ClientForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            myClientControl.logout();

        }
        

        //If registration is successful show login form.
        void myClientControl_RegisterResult(object sender, ClientEventArgs e)
        {
            if (e.Error == null)
            {
                Invoke((MethodInvoker)SafeRegisterResult);
            }
            else
            {
                MessageBox.Show(e.Error.ErrorMessage);
            }
        }

        private void SafeRegisterResult()
        {
            this.loadLoginForm();
            this.CurrentStatusLabel.Text = "Connected, Registered as " + myClientControl.currentUser.Username;
            this.StatusPanel.BackColor = Color.Gold;
        }
        


        //If login is successful display chatroom window
        void myClientControl_LoginResult(object sender, ClientEventArgs e)
        {

            
            //if there was no error open the chat room, if there was a login error the 
            //login form handler will display
            if (e.Error == null)
            {
                Invoke((MethodInvoker)SafeLoginResult);
                
            }
            else
            {
                MessageBox.Show(e.Error.ErrorMessage);
            }

        }

        private void SafeLoginResult()
        {
            this.loadChatForm();    
            this.CurrentStatusLabel.Text = "Connected, Logged in as " + myClientControl.currentUser.Username;
            this.StatusPanel.BackColor = Color.DarkSeaGreen;
            this.logoutToolStripMenuItem1.Enabled = true;
            this.setStatusToolStripMenuItem.Enabled = true;
            this.registerToolStripMenuItem.Enabled = false;
            
        }


        //If there is a new private message
        void myClientControl_NewPrivateMessage(object sender, ClientEventArgs e)
        {

            Message msg = e.ServerMessage;
            MessageInBody body = (MessageInBody)msg.Body;
            if (e.Error == null)
            {

                Invoke((MethodInvoker)delegate 
                {
                    PrivateMessageForm form = myPrivateMessageForms.Where(f => f.toUsername == body.Sender).FirstOrDefault();
                    if (form == null)
                        this.loadPrivateMessageForm(body.Sender, body.Message);
                    else
                        form.addNewMessage(body.Sender, body.Message);
                
                });
            }

        }
        
        //Loads the login form into the client window.
        private void loadLoginForm()
        {

            this.myLoginForm.TopLevel = false;
            this.ClientDisplayPanel.Controls.Add(myLoginForm);
            this.myLoginForm.Show();
            this.myLoginForm.BringToFront();
            this.registerToolStripMenuItem.Enabled = true;
            this.loginToolStripMenuItem.Enabled = false;
                                    
        }//end loadLoginForm()

               
        //Create and load a new private message window
        private PrivateMessageForm loadPrivateMessageForm(string username)
        {
            string toUser = username;
            PrivateMessageForm newPrivateMessageForm = new PrivateMessageForm(myClientControl, username);
            newPrivateMessageForm.FormClosed += new FormClosedEventHandler(newPrivateMessageForm_FormClosed);
            this.myPrivateMessageForms.Add(newPrivateMessageForm);
            newPrivateMessageForm.Show();
            return newPrivateMessageForm;

        }

        private void loadPrivateMessageForm(string username, string message)
        {
            PrivateMessageForm form = loadPrivateMessageForm(username);
            form.addNewMessage(username, message);
        }

        void newPrivateMessageForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (myPrivateMessageForms.Contains((PrivateMessageForm)sender))
                myPrivateMessageForms.Remove((PrivateMessageForm)sender);
        }

        
        //Loads the chat room form into the client window
        private void loadChatForm()
        {
            
            ChatRoomForm newChatWindow = new ChatRoomForm(myClientControl, "Public Room");
            newChatWindow.SelectedUser += new EventHandler(newChatWindow_SelectedUser);
            newChatWindow.TopLevel = false;
            this.ClientDisplayPanel.Controls.Add(newChatWindow);
            newChatWindow.Show();
            newChatWindow.BringToFront();
            this.myChatRoomForms.Add(newChatWindow);
           
        }

        void newChatWindow_SelectedUser(object sender, EventArgs e)
        {
            this.privateMessageToolStripMenuItem.Enabled = true;
            currentChatRoom = this.myChatRoomForms[0];            
           
        }//end loadChatForm()



        //Loads the register form into the client window
        private void loadRegisterForm()
        {

            this.myRegisterForm.TopLevel = false;
            this.ClientDisplayPanel.Controls.Add(myRegisterForm);
            this.myRegisterForm.Show();
            this.myRegisterForm.BringToFront();
            this.loginToolStripMenuItem.Enabled = true;
            this.registerToolStripMenuItem.Enabled = false;

        }//end loadRegisterForm()



        //Handles click event for the RegisterButton
        private void RegisterButton_Click(object sender, EventArgs e)
        {

            this.loadRegisterForm();

        }



        //Handles click event for the LoginButton
        private void LoginButton_Click(object sender, EventArgs e)
        {

            this.loadLoginForm();

        }



        //Handles click event for the register item on the menu strip
        private void registerToolStripMenuItem_Click(object sender, EventArgs e)
        {

            this.loadRegisterForm();            

        }



        //Handles click event for the login item on the menu strip
        private void loginToolStripMenuItem_Click(object sender, EventArgs e)
        {

            this.loadLoginForm();
            
        }


        //Handles click event for the exit item on the menu strip
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            myClientControl.logout();
            this.Close();        
        }


        //Handles click event for logout item on menu strip
        private void logoutToolStripMenuItem1_Click(object sender, EventArgs e)
        {

            myClientControl.logout();

        }


        //Handles when client receives logout ack
        void myClientControl_LogoutResult(object sender, ClientEventArgs e)
        {

            //if there are no logout errors
            if (e.Error == null)
            {
                Invoke((MethodInvoker)SafeLogoutResult);
            }

        }

        void SafeLogoutResult()
        {
            this.loadLoginForm();
            this.CurrentStatusLabel.Text = "Disconnected, Registered as " + myClientControl.currentUser.Username;
            this.StatusPanel.BackColor = Color.LightSalmon;
        }


        //Handle click event for private message menu item
        private void privateMessageToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PrivateMessageForm form = myPrivateMessageForms.Where(f => f.toUsername == currentChatRoom.getSelectedUser()).FirstOrDefault();
            if (form != null)
                form.Focus();
            else
                this.loadPrivateMessageForm(currentChatRoom.getSelectedUser());

        }


        //Handle click event for set status away menu item
        private void awayToolStripMenuItem_Click(object sender, EventArgs e)
        {

            myClientControl.setStatus("Away", "I am away");
            this.CurrentStatusLabel.Text = "Connected, Away - I am away.";
            this.StatusPanel.BackColor = Color.Silver;
            
        }


        //Handle click event for set status online menu item
        private void onlineToolStripMenuItem_Click(object sender, EventArgs e)
        {

            myClientControl.setStatus("Online", "I am online");
            this.CurrentStatusLabel.Text = "Connected, Logged in as " + myClientControl.currentUser.Username;
            this.StatusPanel.BackColor = Color.DarkSeaGreen;
            
        }
                

    }
}
